package com.module.ble.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.viewpager2.widget.ViewPager2
import com.common.app.R
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.dp2px
import com.common.base.utils.ViewUtils.getColor
import com.module.ble.data.bean.CusChartData

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：12/7/2025
 *
 * 描述：睡眠分期图表 根据UI图片设计的睡眠阶段可视化组件
 *
 * 数据结构说明：
 * - dataValues: 睡眠数据数组
 * - mRowCount: Y轴行数，决定图表垂直分割
 * - CusChartData.mOrder: 数据块在Y轴的行位置（0,1,2,3,4...从下到上）
 * - CusChartData.status: 睡眠状态，决定颜色（0,清醒(离床) 1:快速眼动 2:浅睡 3:深睡 4:未佩戴  101:小睡（自用） -999：未知（自用））
 * - CusChartData.timeLong: 时长，决定数据块的宽度比例
 *
 * 修订历史：
 * - 添加触摸实线功能，支持手指左右滑动触摸交互
 *
 */
class SleepStageChart @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 触摸回调接口
    interface OnSleepStageTouchListener {
        /**
         * 触摸到睡眠阶段时的回调
         * @param stageData 睡眠阶段数据
         * @param stageName 阶段名称
         */
        fun onStageTouch(stageData: CusChartData, stageName: String)

        /**
         * 手指离开图表时的回调
         */
        fun onTouchReleased()
    }

    // 数据相关
    private var dataValues = mutableListOf<CusChartData>()
    private var mRowCount = 4 // Y轴行数，默认4行
    private var touchListener: OnSleepStageTouchListener? = null

    // 绘制相关的Paint对象
    private lateinit var stagePaint: Paint // 睡眠阶段块画笔
    private lateinit var backgroundPaint: Paint // 背景画笔
    private lateinit var borderPaint: Paint // 行分割线画笔
    private lateinit var touchLinePaint: Paint // 触摸实线画笔

    // 睡眠阶段颜色配置（根据图片UI设计）睡眠质量 -1,未佩戴 0,清醒 1:快速眼动 2:浅睡 3:深睡  101:小睡（自用） -999：未知
    private val sleepStageColors = mapOf(
        -999 to getColor(R.color.color_F5F5F5), // 未知
        -2 to getColor(R.color.color_d9d9d9), // 离床 - 浅灰色
        4 to getColor(R.color.color_d9d9d9), // 未佩戴 - 浅灰色
        0 to getColor(R.color.c_ffbfff), // 清醒 - 粉色
        1 to getColor(R.color.c_cc99ff), // 快速眼动 - 浅紫色
        2 to getColor(R.color.c_9966ff), // 浅睡 - 紫色
        3 to getColor(R.color.c_6666cc),  // 深睡 - 深紫色
    )

    // 睡眠阶段名称
    private val sleepStageNames = mapOf(
        -999 to "未知",
        -2 to "离床",
        4 to "未佩戴",
        0 to "快速眼动",
        1 to "清醒",
        2 to "浅睡",
        3 to "深睡"
    )

    // 触摸相关
    private var isTouching = false
    private var touchedStageIndex = -1
    private var touchLineX = 0f // 触摸实线的X坐标
    private var isTouchEnabled = true // 触摸总开关，默认开启

    init {
        // 获取自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SleepStageChart)
        mRowCount = typedArray.getInt(R.styleable.SleepStageChart_sleep_rowCount, mRowCount)
        typedArray.recycle()

        initPaint()
    }

    private fun initPaint() {
        stagePaint = Paint().apply {
            style = Paint.Style.FILL
            isAntiAlias = true
        }

        backgroundPaint = Paint().apply {
            style = Paint.Style.FILL
            color = getColor(R.color.color_F5F5F5)
            isAntiAlias = true
        }

        borderPaint = Paint().apply {
            style = Paint.Style.STROKE
            strokeWidth = dp2px(0.5f)
            color = getColor(R.color.color_E0E0E0)
            isAntiAlias = true
        }

        // 初始化触摸实线画笔
        touchLinePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            color = getColor(android.R.color.black)
            strokeWidth = dp2px(1f)
            style = Paint.Style.STROKE
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val desiredWidth = dp2px(350f).toInt()
        val desiredHeight = dp2px(200f).toInt()

        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)

        val width = when (widthMode) {
            MeasureSpec.EXACTLY -> widthSize
            MeasureSpec.AT_MOST -> minOf(desiredWidth, widthSize)
            else -> desiredWidth
        }

        val height = when (heightMode) {
            MeasureSpec.EXACTLY -> heightSize
            MeasureSpec.AT_MOST -> minOf(desiredHeight, heightSize)
            else -> desiredHeight
        }

        setMeasuredDimension(width, height)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 绘制背景
        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), backgroundPaint)

        // 绘制睡眠阶段数据块
        drawSleepStages(canvas)

        // 绘制触摸实线（在数据块之后绘制，确保在最上层）
        if (isTouching && touchedStageIndex >= 0) {
            drawTouchLine(canvas)
        }

//        // 绘制行分割线
//        drawRowDividers(canvas)
    }

    /**
     * 绘制睡眠阶段数据块
     */
    private fun drawSleepStages(canvas: Canvas) {
        if (dataValues.isEmpty()) return

        // 计算总时长用于比例计算
        val totalDuration = dataValues.sumOf { it.timeLong }
        if (totalDuration <= 0) return

        val chartWidth = width
        val chartHeight = height
        val rowHeight = chartHeight / mRowCount

        var currentX = 0f

        dataValues.forEachIndexed { index, stageData ->
            // 计算数据块宽度（基于时长比例）
            val blockWidth = (stageData.timeLong.toFloat() / totalDuration) * chartWidth

            // 计算Y位置（mOrder决定行位置，从下到上：0,1,2,3,4...）
            val rowIndex = stageData.mOrder.coerceIn(0, mRowCount - 1)
            val blockTop = (mRowCount - 1 - rowIndex) * rowHeight
            val blockBottom = blockTop + rowHeight

            // 设置颜色
            stagePaint.color = sleepStageColors[stageData.status] ?: getColor(R.color.color_F5F5F5)

            // 如果是被触摸的块，增加透明度效果
            if (index == touchedStageIndex) {
                stagePaint.alpha = 180
            } else {
                stagePaint.alpha = 255
            }

            // 绘制数据块
            val rect = RectF(currentX, blockTop.toFloat(), currentX + blockWidth, blockBottom.toFloat())
            canvas.drawRect(rect, stagePaint)

            currentX += blockWidth
        }
    }

    /**
     * 绘制触摸实线
     */
    private fun drawTouchLine(canvas: Canvas) {
        if (touchedStageIndex < 0 || touchedStageIndex >= dataValues.size) return

        // 计算触摸数据块的中心X坐标
        val totalDuration = dataValues.sumOf { it.timeLong }
        if (totalDuration <= 0) return

        val chartWidth = width
        var currentX = 0f

        // 找到触摸的数据块并计算其中心X坐标
        for (i in 0..touchedStageIndex) {
            val blockWidth = (dataValues[i].timeLong.toFloat() / totalDuration) * chartWidth
            if (i == touchedStageIndex) {
                touchLineX = currentX + blockWidth / 2
                break
            }
            currentX += blockWidth
        }

        // 绘制从顶部到底部的黑色实线
        canvas.drawLine(touchLineX, 0f, touchLineX, height.toFloat(), touchLinePaint)
    }

    /**
     * 绘制行分割线
     */
    private fun drawRowDividers(canvas: Canvas) {
        val chartWidth = width
        val chartHeight = height
        val rowHeight = chartHeight / mRowCount

        for (i in 1 until mRowCount) {
            val y = i * rowHeight
            canvas.drawLine(
                0f, y.toFloat(),
                chartWidth.toFloat(), y.toFloat(),
                borderPaint
            )
        }
    }

    /**
     * 查找ViewPager2
     */
    private fun findViewPager2(): ViewPager2? {
        var parent = this.parent
        while (parent != null) {
            if (parent is ViewPager2) {
                return parent
            }
            parent = parent.parent
        }
        return null
    }

    /**
     * 检查触摸点是否在图表区域内
     */
    private fun isTouchInChartArea(touchX: Float, touchY: Float): Boolean {
        return touchX >= 0 && touchX <= width && touchY >= 0 && touchY <= height
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        // 如果触摸开关关闭，直接透传到父视图
        if (!isTouchEnabled) {
            return super.onTouchEvent(event)
        }

        if (dataValues.isNullOrEmpty()) return true//无数据是直接透传触摸

        val viewPager2 = findViewPager2()

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                if (isTouchInChartArea(event.x, event.y)) {
                    // 禁用ViewPager2的用户输入
                    viewPager2?.isUserInputEnabled = false
                    parent?.requestDisallowInterceptTouchEvent(true)

                    val touchedIndex = findTouchedStage(event.x, event.y)
                    if (touchedIndex >= 0) {
                        isTouching = true
                        touchedStageIndex = touchedIndex
                        touchLineX = event.x

                        val stageData = dataValues[touchedIndex]
                        val stageName = sleepStageNames[stageData.status] ?: "未知"
                        touchListener?.onStageTouch(stageData, stageName)

                        invalidate()
                        return true
                    }
                }
            }
            MotionEvent.ACTION_MOVE -> {
                if (isTouching && isTouchInChartArea(event.x, event.y)) {
                    val touchedIndex = findTouchedStage(event.x, event.y)
                    if (touchedIndex >= 0 && touchedIndex != touchedStageIndex) {
                        touchedStageIndex = touchedIndex

                        val stageData = dataValues[touchedIndex]
                        val stageName = sleepStageNames[stageData.status] ?: "未知"
                        touchListener?.onStageTouch(stageData, stageName)
                    }
                    invalidate()
                    return true
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                // 重新启用ViewPager2的用户输入
                viewPager2?.isUserInputEnabled = true
                parent?.requestDisallowInterceptTouchEvent(false)

                if (isTouching) {
                    isTouching = false
                    touchedStageIndex = -1
                    touchListener?.onTouchReleased()
                    invalidate()
                    return true
                }
            }
        }
        return super.onTouchEvent(event)
    }

    /**
     * 查找被触摸的睡眠阶段
     */
    private fun findTouchedStage(touchX: Float, touchY: Float): Int {
        if (dataValues.isEmpty()) return -1

        val totalDuration = dataValues.sumOf { it.timeLong }
        if (totalDuration <= 0) return -1

        val chartWidth = width
//        val chartHeight = height
//        val rowHeight = chartHeight / mRowCount

        var currentX = 0f

        dataValues.forEachIndexed { index, stageData ->
            val blockWidth = (stageData.timeLong.toFloat() / totalDuration) * chartWidth
//            val rowIndex = stageData.mOrder.coerceIn(0, mRowCount - 1)
//            val blockTop = (mRowCount - 1 - rowIndex) * rowHeight
//            val blockBottom = blockTop + rowHeight

//            if (touchX >= currentX && touchX <= currentX + blockWidth &&
//                touchY >= blockTop && touchY <= blockBottom) {
            if (touchX >= currentX && touchX <= currentX + blockWidth) {
                return index
            }

            currentX += blockWidth
        }

        return -1
    }

    // 公共API方法
    /**
     * 设置睡眠阶段数据
     * @param sleepData 睡眠数据列表
     */
    fun setSleepStageData(sleepData: List<CusChartData>) {
        dataValues.clear()
        dataValues.addAll(sleepData)
        invalidate()
    }

    /**
     * 设置Y轴行数
     * @param rowCount 行数
     */
    fun setRowCount(rowCount: Int) {
        if (mRowCount != rowCount && rowCount > 0) {
            mRowCount = rowCount
            invalidate()
        }
    }

    /**
     * 获取当前行数
     */
    fun getRowCount(): Int = mRowCount

    /**
     * 设置触摸监听器
     */
    fun setOnSleepStageTouchListener(listener: OnSleepStageTouchListener?) {
        this.touchListener = listener
    }

    /**
     * 获取当前数据
     */
    fun getSleepStageData(): List<CusChartData> {
        return dataValues.toList()
    }

    /**
     * 获取睡眠阶段名称
     */
    fun getStageName(status: Int): String {
        return sleepStageNames[status] ?: "未知"
    }

    /**
     * 获取睡眠阶段颜色
     */
    fun getStageColor(status: Int): Int {
        return sleepStageColors[status] ?: getColor(R.color.color_F5F5F5)
    }

    /**
     * 设置触摸开关
     * @param enabled true为启用触摸，false为禁用触摸
     */
    fun setTouchEnabled(enabled: Boolean) {
        if (isTouchEnabled != enabled) {
            isTouchEnabled = enabled
            // 如果禁用触摸时正在触摸，需要重置触摸状态
            if (!enabled && isTouching) {
                isTouching = false
                touchedStageIndex = -1
                touchListener?.onTouchReleased()
                invalidate()
            }
        }
    }

    /**
     * 获取触摸开关状态
     */
    fun isTouchEnabled(): Boolean = isTouchEnabled
}